<?php
/**
 * Created by PHPStorm
 * User: xiest
 * Date: 2021/8/9
 * Email: <939369942@qq.com>
 */
namespace basic\services;

class LocationService{
    public function __construct($config)
    {
        $this->config = $config;
    }

    public static function create()
    {
        return new self(self::getConfig());
    }

    public static function getConfig()
    {
        return ['key'=>env('MAPKEY.TX_MAP_KEY')];
    }

    /**
     * 地理位置转换为坐标
     * @param string $address
     * @return mixed|null
     * User: xiest
     * Date: 2021/8/9
     */
    public function address2Location(string $address)
    {
        $data = [
            'address'=>$address,
            'key'=>$this->config['key'],
        ];
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?".
            http_build_query($data);
        $http = HttpService::getRequest($url);
        $data = json_decode($http,true);
        if(isset($data['status']) && $data['status'] == 0) return $data['result'];
        else return null;
    }

    /**
     * 坐标转换地理位置
     * @param $lat
     * @param $lng
     * @return array|mixed
     * User: xiest
     * Date: 2021/10/12
     */
    public function location2Address($lat,$lng)
    {
        $data = [
            'location'=>"{$lat},{$lng}",
            'key'=>$this->config['key'],
        ];
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?".
            http_build_query($data);

        $http = HttpService::getRequest($url);
        $data = json_decode($http,true);

        if(isset($data['status']) && $data['status'] == 0) return $data['result'];
        else return [];
    }

}